﻿
class AreaCut{
	private var mapBoxH:Array;
	private var mapBoxV:Array;	private var MCa:Array;
	private var W:Number;
	private var H:Number;
	private var N:Number;
	private var paceW:Number;
	private var paceH:Number;
	public function AreaCut(w:Number,h:Number,n:Number){
		W=w;
		H=h;
		N=n;
		Init();
	}
	private function Init(){
		paceW=W/N;
		paceH=H/N;
		mapBoxH=new Array();
		mapBoxV=new Array();
		MCa=new Array();
		for(var i=0;i<N;i++){
			mapBoxH.push({wz1:i*paceW,wz2:(i+1)*paceW});
			mapBoxV.push({wz1:i*paceH,wz2:(i+1)*paceH});
			MCa[i]=new Array(N);
			for(var l=0;l<N;l++){
				MCa[i][l]={};
			}
		}
	}
	public function DrawGrid(tag:MovieClip){
		tag.lineStyle(0,0x999999,80);
		for(var i=0;i<=N;i++){
			tag.moveTo(i*paceW,0);
			tag.lineTo(i*paceW,H);
		}
		for(var i=0;i<=N;i++){
			tag.moveTo(0,i*paceH);
			tag.lineTo(W,i*paceH);
		}
	}
	public function SingMap(mc:MovieClip){
		var lf:Number=mc._x;
		var rt:Number=mc._x+mc._width;
		var tp:Number=mc._y;
		var bottom:Number=mc._y+mc._height;
		
		//mc.__thX=[getWZ(0,N-1,true,lf),getWZ(0,N-1,true,rt)];
		//mc.__thY=[getWZ(0,N-1,false,tp),getWZ(0,N-1,false,bottom)];
		if(mc.__thX!=undefined && mc.__thX!=undefined){
			delete MCa[mc.__thX][mc.__thY][mc._name];
		}
		mc.__thX=getWZ(0,N-1,true,lf);
		mc.__thY=getWZ(0,N-1,false,tp);
		MCa[mc.__thX][mc.__thY][mc._name]=mc;
	}
	public function hitTestMCs(mc:MovieClip):Object{
		if(mc.__thX==undefined){SingMap(mc);}
		//FixMcMapWZ(mc1);
		//FixMcMapWZ(mc2);
		//if(mc1.__thX[0]>mc2.__thX[1] || mc1.__thX[1]<mc2.__thX[0]){
			//return false;
		//}else{
			//if(mc1.__thY[0]>mc2.__thY[1] || mc1.__thY[1]<mc2.__thY[0]){
				//return false;
			//}else{
				//return true;
			//}
		//}
		return MCa[mc.__thX][mc.__thY];
	}
	private function FixMcMapWZ(mc:MovieClip){
		if(mc.__thX[1]==-1)
		{
			mc.__thX[1]=mc.__thX[0];
		}		
		if(mc.__thY[1]==-1)
		{
			mc.__thY[1]=mc.__thY[0];
		}
	}
	private function getWZ(st:Number, et:Number, hv:Boolean, v:Number):Number {
	var l = et-st;
	var array = mapBoxV;
	if (hv) {
		array = mapBoxH;
	}
	if (l < 1) {
		if (array[et].wz1<=v && array[et].wz2>=v) {
			return et;
		} else if (array[st].wz1<=v && array[st].wz2>=v) {
			return st;
		} else {
			return -1;
		}
	}
	var mn = int((st+et)/2);
	if (array[mn].wz1<=v && array[mn].wz2>=v) {
		return mn;
	} else if (array[mn].wz1>v) {
		return getWZ(st, mn-1, hv, v);
	} else if (array[mn].wz2<=v) {
		return getWZ((mn+1), et, hv, v);
	}
}
}